package cn.nicklemay.interview.algorithm;

import java.util.Hashtable;
import java.util.Scanner;

public class LRUCache
{
    private Hashtable<Integer, DLinkedNode>
            cache = new Hashtable<>();
    private int count;
    private int capacity;
    private DLinkedNode head, tail;

    private void addToFirstNode(DLinkedNode node){
        node.pre = head;
        node.post = head.post;

        head.post.pre = node;
        head.post = node;
    }


    private void removeNode(DLinkedNode node){
        DLinkedNode pre = node.pre;
        DLinkedNode post = node.post;

        pre.post = post;
        post.pre = pre;
    }

    private void moveToHead(DLinkedNode node){
        this.removeNode(node);
        this.addToFirstNode(node);
    }

    private DLinkedNode popTail(){
        DLinkedNode res = tail.pre;
        this.removeNode(res);
        return res;
    }

    public LRUCache(int capacity) {
        this.count = 0;
        this.capacity = capacity;

        head = new DLinkedNode();
        head.pre = null;

        tail = new DLinkedNode();
        tail.post = null;

        head.post = tail;
        tail.pre = head;
    }

    public int get(int key) {
        DLinkedNode node = cache.get(key);
        if(node == null){
            System.out.println(-1);
            return -1;
        } else {
            System.out.println(node.value);
        }
        this.moveToHead(node);
        return node.value;
    }

    public void put(int key, int value) {
        DLinkedNode node = cache.get(key);
        if(node == null){
            DLinkedNode newNode = new DLinkedNode();
            newNode.key = key;
            newNode.value = value;
            this.cache.put(key, newNode);
            this.addToFirstNode(newNode);
            ++count;
            if(count > capacity){
                DLinkedNode tail = this.popTail();
                this.cache.remove(tail.key);
                --count;
            }
        }else{
            node.value = value;
            this.moveToHead(node);
        }

    }

    class DLinkedNode {
        int key;
        int value;
        DLinkedNode pre;
        DLinkedNode post;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int c = scanner.nextInt();
        LRUCache lruCache = new LRUCache(c);
        String s;
        while ((s=scanner.next()) != null) {
            if ("p".equals(s)) {
                lruCache.put(Integer.valueOf(scanner.nextInt()), Integer.valueOf(scanner.nextInt()));
            } else {
                lruCache.get(Integer.valueOf(scanner.nextInt()));
            }
        }
        scanner.close();
    }
}
